#include "downloadhelper.h"
#include <QFileInfo>

bool downloadHelper::CheckedFile(QString fileName)
{
    if(fileName.isEmpty())
         return false;

     if(QFile::exists(fileName))
     {
         //qDebug() << tr("删除存在文件 %1\n").arg(fileName);
         QFile::remove(fileName);
     }
     if(file)
     {
         delete file;
         file = nullptr;
     }

     file = new QFile(fileName);
     if(!file->open(QFile::OpenModeFlag::WriteOnly))
     {
         //Create new file error!
         delete file;
         file = nullptr;

         //if(QMessageBox::question(this, tr("错误信息"), tr("创建文件 %1 失败!").arg(fileName)))
         return false;
     }

     return true;
}

void downloadHelper::downloadFile(QUrl fileUrl)
{
    QFileInfo info(fileUrl.path());

    if(!CheckedFile(info.fileName()))
        return;//失败

    Reply = Manager.get(QNetworkRequest(fileUrl));
    connect(Reply, SIGNAL(readyRead()), this, SLOT(WriteFile()));
    connect(Reply, SIGNAL(finished()), this, SLOT(WriteFileEnd()));
}

void downloadHelper::WriteFile()
{
    if(!file)
        return;
    file->write(Reply->readAll());
    file->flush();
}

void downloadHelper::WriteFileEnd()
{
    if(!file)
        return;

    file->write(Reply->readAll());
    file->flush();
    file->close();

    delete file;
    file = nullptr;

    Reply->deleteLater();
    Reply = nullptr;

    emit SendMessageFileDownEnd();
}
